<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>GeoFence with Tencent Map</title>

  <script charset="utf-8" src="https://map.qq.com/api/gljs?libraries=tools&v=1.exp&key=L2DBZ-UK33U-HLGVI-42B2I-7COMK-RBB43"></script>

  <!-- 替换 YOUR_TENCENT_MAP_KEY 为你申请的腾讯地图 API Key -->
  <style>
    #map {
      width: 100%;
      height: 500px;
    }
    #info {
      margin: 20px 0;
    }
  </style>
</head>
<body>
<h1>GeoFence Example with Tencent Map</h1>
<div id="map"></div>
<div id="info"></div>
<script>
  // 初始化地图
  var map = new TMap.Map(document.getElementById('map'), {
    center: new TMap.LatLng(39.984104, 116.307503), // 设置中心点
    zoom: 14 // 设置缩放级别
  });

  // 创建电子围栏 (圆形区域)
  var fenceCenter = new TMap.LatLng(39.984104, 116.307503); // 围栏中心点坐标
  var fenceRadius = 500; // 围栏半径 (米)

  var circle = new TMap.MultiCircle({
    map: map,
    geometries: [{
      center: fenceCenter,
      radius: fenceRadius,
      color: '#FF0000',
      borderColor: '#FF0000',
      borderWidth: 2,
      fillOpacity: 0.2
    }]
  });

  // 模拟车辆位置
  var vehiclePosition = new TMap.LatLng(39.985, 116.308);

  // 添加车辆标记
  var marker = new TMap.MultiMarker({
    map: map,
    geometries: [{
      id: 'vehicle',
      position: vehiclePosition,
      icon: 'https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/car.png',
      properties: {
        title: 'Vehicle'
      }
    }]
  });

  // 计算车辆是否在围栏内
  function isWithinFence(vehiclePos, fenceCenter, fenceRadius) {
    var distance = TMap.GeometryUtil.distanceBetween(vehiclePos, fenceCenter);
    return distance <= fenceRadius;
  }

  // 检查车辆位置并显示结果
  var info = document.getElementById('info');
  if (isWithinFence(vehiclePosition, fenceCenter, fenceRadius)) {
    info.innerHTML = "Vehicle is within the geofence.";
  } else {
    info.innerHTML = "Vehicle is outside the geofence.";
  }
</script>
</body>
</html>
